package com.guchenbo.example.bigdata;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;

/**
 * @Author penglai
 * @Date 2016/9/28.
 */
public class BigDataTest {

    public static List<ListenBean> readBigData(String filePath) {
        List<ListenBean> list = new ArrayList();
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath));
            FileReader fileReader = new FileReader(filePath);
            BufferedReader reader = new BufferedReader(fileReader);

            while ((reader.read()) != -1) {
                list.add(ListenBean.buildWithInfo(reader.readLine()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void noFork(List<ListenBean> source) {
        List<ListenBean> ret = new ArrayList<ListenBean>();
        for (int i = 0; i < source.size(); i++) {
            ret.add(source.get(i));
        }
        System.out.println(ret.size());
    }

    public static void fork1(List<ListenBean> source) throws ExecutionException, InterruptedException {
        ForkTask1 task = new ForkTask1(0, source.size(), source);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future<List<ListenBean>> future = forkJoinPool.submit(task);
        List<ListenBean> dest = future.get();
        System.out.println(dest.size());
    }

    public static void fork2(List<ListenBean> source) throws ExecutionException, InterruptedException {
        ForkTaskMap1 task = new ForkTaskMap1(0, source.size(), source);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future<Map<Integer,List<ListenBean>>> future = forkJoinPool.submit(task);
        Map<Integer,List<ListenBean>> dest = future.get();

        System.out.println(dest.size());
        for (Map.Entry<Integer, List<ListenBean>> entry : dest.entrySet()) {
//            System.out.println(entry.getKey());
        }
    }

    public static void main(String[] args) {
        String filePath = "/Users/penglai/Documents/history_10.txt";

        try {
            List<ListenBean> source = readBigData(filePath);
//            noFork(source);
            fork1(source);
//            fork2(source);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
